package com.ly.mpayment.rest.system;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;

import com.ly.mpayment.persist.entity.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ly.mpayment.core.util.BigUtil;
import com.ly.mpayment.core.util.Config;
import com.ly.mpayment.core.util.CookieRedis;
import com.ly.mpayment.core.util.DateUtils;
import com.ly.mpayment.core.util.ExportExcelUtil;
import com.ly.mpayment.core.util.FileUtils;
import com.ly.mpayment.core.util.JsonUtils;
import com.ly.mpayment.core.util.MapUtil;
import com.ly.mpayment.core.util.ResultMessage;
import com.ly.mpayment.core.util.StringUtils;
import com.ly.mpayment.core.util.UserUtil;
import com.ly.mpayment.persist.service.businesstype.IBusinessTypeService;
import com.ly.mpayment.persist.service.downshopproduct.IDownShopProductService;
import com.ly.mpayment.persist.service.matchingstrategy.IMatchingStrategyService;
import com.ly.mpayment.persist.service.operators.IOperatorsService;
import com.ly.mpayment.persist.service.provincialinformation.IProvincialInformationService;
import com.ly.mpayment.persist.service.user.IUserService;
import com.ly.mpayment.rest.AbsRest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Component
@Path("system/downproduct/")
public class DownProductRest extends AbsRest {

	@Autowired
	IUserService userService;

	@Autowired
	IProvincialInformationService proService;

	@Autowired
	IOperatorsService operatorService;

	@Autowired
	IBusinessTypeService busService;

	@Autowired
	IDownShopProductService productService;

	@Autowired
	IMatchingStrategyService matchService;

//	@Autowired
//	IDownShopInfoService shopInfoService;

	@Path("addDownProduct")
	@POST
	public String addDownProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "provinceuuid","operatoruid","busuuid","useruuid","productCode",
				"downfacevalue","fastchargetype","downfailnum","downtimeinterva","remark","discount","price","discountAmount","productName","validity");
		if(result == null){
		      JSONObject json = JsonUtils.converToJson(data);
		      Operators operator = operatorService.findById(json.getString("operatoruid"));
		      if(operator != null){
		    	  ProvincialInformation pro = proService.findById(json.getString("provinceuuid"));
			      if(pro != null){
			    	  BusinessType busType = busService.findById(json.getString("busuuid"));
			    	  if(busType != null){
			    		  User user = userService.findByUserid(json.getString("useruuid"));
			    		  if(user != null && UserUtil.checkRoleDown(user)){

			    			  DownShopProduct old = this.productService.searchBatchProduct(json.getString("operatoruid"), json.getString("provinceuuid"),
			    					  json.getString("busuuid"), json.getString("useruuid"), json.getString("downfacevalue").trim(), BigUtil.getBigDecimal(json.getString("price").trim()),json.getString("productCode").trim());
			    			  if(old != null){
			    				  return ResultMessage.getFailt(ResultMessage.productCodeexistError);
			    			  }

			    			  DownShopProduct product = null;
			    			  product = new DownShopProduct();
			    			  product.setBusinessType(busType);
			    			  product.setOperators(operator);
			    			  product.setProvincialInformation(pro);
			    			  product.setUser(user);
			    			  product.setProductCode(json.getString("productCode").trim());
			    			  product.setDownfacevalue(json.getString("downfacevalue").trim());
			    			  product.setPrice(BigUtil.getBigDecimal(json.getString("price").trim()));
			    			  product.setFastchargetype(json.getInt("fastchargetype"));
			    			  product.setDownfailnum(json.getInt("downfailnum"));
			    			  product.setDowntimeinterva(json.getInt("downtimeinterva"));
			    			  product.setRemark(json.getString("remark"));
			    			  product.setDiscount(BigUtil.getBigDecimal(json.getString("discount").trim()));
			    			  product.setStatus(Config.productStatus[1]);
			    			  product.setDiscountAmount(BigUtil.getBigDecimal(json.getString("discountAmount").trim()));
			    			  product.setAuto(Config.autoStrategy[0]);
			    			  product.setProductName(json.getString("productName"));
			    			  product.setValidity((json.getString("validity")));
							  product.setCityName(json.containsKey("cityName") ? json.getString("cityName") : "");
//			    			  product.setDownprouuid(StringUtils.getBatchNO());
			    			  String token = request.getHeader("token");
			    				if (token != null) {
			    					DecodedJWT jwt;
		    						jwt = JWT.decode(token);
		    						if (jwt != null) {
		    							JSONObject jsonUser = JsonUtils.converToJson(jwt.getSubject());
		    							if (json != null) {
		    								User userAdmin = userService.findByUserid(jsonUser.getString(Config.tokenSignAttr));
		    								 if(productService.addDownshopproduct(product,userAdmin)){
		    				    				  return ResultMessage.getSucceed(null);
		    				    			  }
		    				    			  return ResultMessage.getFailt("");
		    							}
		    						}
			    				}
			    		  }
			    		  return ResultMessage.getFailt(ResultMessage.shopexistOrUserError);
			    	  }
			    	  return ResultMessage.getFailt(ResultMessage.busError);
			      }
			      return ResultMessage.getFailt(ResultMessage.provincialError);
		      }
		     return ResultMessage.getFailt(ResultMessage.operatorsError);
		}
		return result;
	}
	@Path("addDownBatchProduct")
	@POST
	public String addDownBatchProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "provinceuuid","operatoruid","busuuid","useruuid","fastchargetype","downfailnum","downtimeinterva","products");
		if(result == null){
		      JSONObject json = JsonUtils.converToJson(data);
		      Operators operator = operatorService.findById(json.getString("operatoruid"));
		      if(operator != null){
		    	  ProvincialInformation pro = proService.findById(json.getString("provinceuuid"));
			      if(pro != null){
			    	  BusinessType busType = busService.findById(json.getString("busuuid"));
			    	  if(busType != null){
			    		  User user = userService.findByUserid(json.getString("useruuid"));
			    		  if(user != null && UserUtil.checkRoleDown(user)){
			    			  JSONArray pros = json.getJSONArray("products");
			    			  boolean temp = false;
			    			  if(pros != null && !pros.isEmpty()){
			    				  String addProductResult = "";
			    				  for(int i = 0 ; i < pros.size(); i++){
			    					 DownShopProduct product = this.productService.searchBatchProduct(json.getString("operatoruid"), json.getString("provinceuuid"), json.getString("busuuid"),
			    							  json.getString("useruuid"), (pros.getJSONObject(i).getString("downfacevalue")),BigUtil.getBigDecimal(pros.getJSONObject(i).getString("price")),pros.getJSONObject(i).getString("productCode").trim());
			    					  if(product != null){
			    						  temp = true;
			    						  addProductResult += "面值:"+pros.getJSONObject(i).getString("downfacevalue").concat(",原价:").concat(pros.getJSONObject(i).getString("price").concat("  "));
			    					  }
			    				  }
			    				  if(temp){
			    					  return ResultMessage.getFailt(addProductResult.concat(Config.exist));
			    				  }

			    				  //
			    				  for(int i = 0 ; i < pros.size(); i++){
			    					  DownShopProduct product = new DownShopProduct();
					    			  product.setBusinessType(busType);
					    			  product.setOperators(operator);
					    			  product.setProvincialInformation(pro);
					    			  product.setUser(user);
					    			  product.setProductCode(pros.getJSONObject(i).getString("downfacevalue").trim());
					    			  product.setFastchargetype(json.getInt("fastchargetype"));
					    			  product.setDownfailnum(json.getInt("downfailnum"));
					    			  product.setDowntimeinterva(json.getInt("downtimeinterva"));
					    			  product.setDownfacevalue(pros.getJSONObject(i).getString("downfacevalue"));
					    			  product.setPrice(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("price").trim()));
					    			  product.setDiscount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discount").trim()));
					    			  product.setDiscountAmount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discountAmount").trim()));
					    			  product.setStatus(Config.productStatus[1]);
					    			  product.setAuto(Config.autoStrategy[0]);
					    			  product.setProductName(pros.getJSONObject(i).getString("productName"));
									  product.setCityName(json.containsKey("cityName") ? json.getString("cityName") : "");
					    			  String token = request.getHeader("token");
					    				if (token != null) {
					    					DecodedJWT jwt;
				    						jwt = JWT.decode(token);
				    						if (jwt != null) {
				    							JSONObject jsonUser = JsonUtils.converToJson(jwt.getSubject());
				    							if (json != null) {
				    								User userAdmin = userService.findByUserid(jsonUser.getString(Config.tokenSignAttr));
				    								if(!productService.addDownshopproduct(product,userAdmin)){
				    									return ResultMessage.getFailt("");
				    				    			}
				    							}
				    						}
					    				}
			    				  }
			    				  return ResultMessage.getSucceed(null);
			    			  }
			    			  return ResultMessage.getFailt(ResultMessage.productBatchError);
			    		  }
			    		  return ResultMessage.getFailt(ResultMessage.shopexistOrUserError);
			    	  }
			    	  return ResultMessage.getFailt(ResultMessage.busError);
			      }
			      return ResultMessage.getFailt(ResultMessage.provincialError);
		      }
		     return ResultMessage.getFailt(ResultMessage.operatorsError);
		}
		return result;
	}

	@Path("copyDownBatchProduct")
	@POST
	public String copyDownBatchProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "provinceuuid","operatoruid","busuuid","useruuid","fastchargetype","downfailnum","downtimeinterva","products");
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			Operators operator = operatorService.findById(json.getString("operatoruid"));
			if(operator != null){
				ProvincialInformation pro = proService.findById(json.getString("provinceuuid"));
				if(pro != null){
					BusinessType busType = busService.findById(json.getString("busuuid"));
					if(busType != null){
						User user = userService.findByUserid(json.getString("touseruuid"));
						if(user != null && UserUtil.checkRoleDown(user)){
							JSONArray pros = json.getJSONArray("products");
							boolean temp = false;
							if(pros != null && !pros.isEmpty()){
								String addProductResult = "";
								for(int i = 0 ; i < pros.size(); i++){
									DownShopProduct product = this.productService.searchBatchProduct(json.getString("operatoruid"), json.getString("provinceuuid"), json.getString("busuuid"),
											json.getString("touseruuid"), (pros.getJSONObject(i).getString("downfacevalue")),BigUtil.getBigDecimal(pros.getJSONObject(i).getString("price")),pros.getJSONObject(i).getString("productCode").trim());
									if(product != null){
										temp = true;
										addProductResult += "面值:"+pros.getJSONObject(i).getString("downfacevalue").concat(",原价:").concat(pros.getJSONObject(i).getString("price").concat("  "));
									}
								}
								if(temp){
									return ResultMessage.getFailt(addProductResult.concat(Config.exist));
								}

								//
								for(int i = 0 ; i < pros.size(); i++){
									DownShopProduct product = new DownShopProduct();
									product.setBusinessType(busType);
									product.setOperators(operator);
									product.setProvincialInformation(pro);
									product.setUser(user);
									product.setProductCode(pros.getJSONObject(i).getString("downfacevalue").trim());
									product.setFastchargetype(json.getInt("fastchargetype"));
									product.setDownfailnum(json.getInt("downfailnum"));
									product.setDowntimeinterva(json.getInt("downtimeinterva"));
									product.setDownfacevalue(pros.getJSONObject(i).getString("downfacevalue"));
									product.setPrice(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("price").trim()));
									product.setDiscount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discount").trim()));
									product.setDiscountAmount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discountAmount").trim()));
									product.setStatus(Config.productStatus[1]);
									product.setAuto(Config.autoStrategy[0]);
									product.setProductName(pros.getJSONObject(i).getString("productName"));
									product.setCityName(json.containsKey("cityName") ? json.getString("cityName") : "");
									String token = request.getHeader("token");
									if (token != null) {
										DecodedJWT jwt;
										jwt = JWT.decode(token);
										if (jwt != null) {
											JSONObject jsonUser = JsonUtils.converToJson(jwt.getSubject());
											if (json != null) {
												User userAdmin = userService.findByUserid(jsonUser.getString(Config.tokenSignAttr));
												if(!productService.addDownshopproduct(product,userAdmin)){
													return ResultMessage.getFailt("");
												}
											}
										}
									}
								}
								return ResultMessage.getSucceed(null);
							}
							return ResultMessage.getFailt(ResultMessage.productBatchError);
						}
						return ResultMessage.getFailt(ResultMessage.shopexistOrUserError);
					}
					return ResultMessage.getFailt(ResultMessage.busError);
				}
				return ResultMessage.getFailt(ResultMessage.provincialError);
			}
			return ResultMessage.getFailt(ResultMessage.operatorsError);
		}
		return result;
	}

	@SuppressWarnings("static-access")
	@Path("findBatchEditDownProduct")
	@POST
	public String findBatchEditDownProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "provinceuuid","operatoruid","busuuid","useruuid","discount");
		if(result == null){
			JSONObject json = JSONObject.fromObject(data);

			if(json.containsKey("useruuid")){
				JSONArray array = json.getJSONArray("useruuid");
				List<String> list = new ArrayList<>();
				for(int i = 0 ; i < array.size();i++){
					list.add("'"+array.getString(i)+"'");
				}
				json.put("useruuid",org.apache.commons.lang.StringUtils.join(list.toArray(),","));
			}

			if(json.containsKey("downfacevalue") && !StringUtils.isBlank(json.getString("downfacevalue"))){
				JSONArray array = json.getJSONArray("downfacevalue");
				List<String> list = new ArrayList<>();
				for(int i = 0 ; i < array.size();i++){
					list.add("'"+array.getString(i)+"'");
				}
				json.put("downfacevalue",org.apache.commons.lang.StringUtils.join(list.toArray(),","));
			}

			return ResultMessage.getSucceed( JsonUtils.convertListToJson(this.productService.findBatchEditUpProduct(
					json.getString("provinceuuid"),json.getString("operatoruid"),json.getString("busuuid"),
					json.getString("useruuid"),json.getString("cityName"),json.getString("discount"),json.getString("downfacevalue")),
					new String[]{"operatorsType","errorCodesForUseruuid","busuuid","","code","operatoruid","provincestatus","provinceuuid","lastlogintime",
							"password","token","userstatus","useruuid","wechatid","busCode","provincecode","businessType","provincialInformation","operators","user"}));
		}
		return result;
	}

	@Path("batchEditDownProduct")
	@POST
	public String batchEditDownProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "provinceuuid","operatoruid","busuuid","useruuid","fastchargetype","downfailnum","downtimeinterva","products");
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			Operators operator = operatorService.findById(json.getString("operatoruid"));
			if(operator != null){
				ProvincialInformation pro = proService.findById(json.getString("provinceuuid"));
				if(pro != null){
					BusinessType busType = busService.findById(json.getString("busuuid"));
					if(busType != null){
						String token = request.getHeader("token");
						if (token != null) {
							DecodedJWT jwt;
							jwt = JWT.decode(token);
							if (jwt != null) {
								JSONObject jsonUser = JsonUtils.converToJson(jwt.getSubject());
								if (json != null) {
									User userAdmin = userService.findByUserid(jsonUser.getString(Config.tokenSignAttr));
									if(userAdmin != null && UserUtil.checkRole(userAdmin)){
										JSONArray pros = json.getJSONArray("products");
										if(pros != null && !pros.isEmpty()){
											for(int i = 0 ; i < pros.size(); i++){
												DownShopProduct product = this.productService.findById(pros.getJSONObject(i).containsKey("downprouuid") ? pros.getJSONObject(i).getString("downprouuid") : "");
												if(product == null ) {
													return ResultMessage.getFailt("未找到产品");
												}
												product.setBusinessType(busType);
												product.setOperators(operator);
												product.setProvincialInformation(pro);
												product.setDownfacevalue(pros.getJSONObject(i).getString("downfacevalue"));
												product.setProductCode(pros.getJSONObject(i).getString("downfacevalue").trim());
												product.setPrice(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("price").trim()));
												product.setDiscount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discount").trim()));
												product.setDiscountAmount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discountAmount").trim()));
												product.setProductName(pros.getJSONObject(i).getString("productName"));
												if(!productService.updateDownshopproduct(product,userAdmin,false)){
													return ResultMessage.getFailt("");
												}
											}
											return ResultMessage.getSucceed(null);
										}
										return ResultMessage.getFailt(ResultMessage.productBatchError);
									}
								}
							}
						}
						return ResultMessage.getFailt(ResultMessage.shopexistOrUserError);
					}
					return ResultMessage.getFailt(ResultMessage.busError);
				}
				return ResultMessage.getFailt(ResultMessage.provincialError);
			}
			return ResultMessage.getFailt(ResultMessage.operatorsError);
		}
		return result;
	}

	@Path("batchEditDownProductAll")
	@POST
	public String batchEditDownProductAll(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "provinceuuid","operatoruid","busuuid","useruuid","fastchargetype","downfailnum","downtimeinterva","products");
		if(result == null){
		      JSONObject json = JsonUtils.converToJson(data);
		      Operators operator = operatorService.findById(json.getString("operatoruid"));
		      if(operator != null){
		    	  ProvincialInformation pro = proService.findById(json.getString("provinceuuid"));
			      if(pro != null){
			    	  BusinessType busType = busService.findById(json.getString("busuuid"));
			    	  if(busType != null){
			    	  	//todo
						  String token = request.getHeader("token");
						  if (token != null) {
							  DecodedJWT jwt;
							  jwt = JWT.decode(token);
							  if (jwt != null) {
								  JSONObject jsonUser = JsonUtils.converToJson(jwt.getSubject());
								  if (json != null) {
									  User user = userService.findByUserid(jsonUser.getString(Config.tokenSignAttr));
									  if(user != null && UserUtil.checkRole(user)){

										  JSONArray pros = json.getJSONArray("products");
										  if(pros != null && !pros.isEmpty()){
											  for(int i = 0 ; i < pros.size(); i++){
												  DownShopProduct product = this.productService.findById(pros.getJSONObject(i).containsKey("downprouuid") ? pros.getJSONObject(i).getString("downprouuid") : "");
												  if(product != null ){
													  product.setBusinessType(busType);
													  product.setOperators(operator);
													  product.setProvincialInformation(pro);
													  product.setDownfacevalue(pros.getJSONObject(i).getString("downfacevalue"));
													  product.setProductCode(pros.getJSONObject(i).getString("downfacevalue").trim());
													  product.setPrice(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("price").trim()));
													  product.setDiscount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discount").trim()));
													  product.setDiscountAmount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discountAmount").trim()));
													  product.setProductName(pros.getJSONObject(i).getString("productName"));

													  if(!productService.updateDownshopproduct(product,user,false)){
														  return ResultMessage.getFailt("");
													  }
												  }
											  }
											  return ResultMessage.getSucceed(null);
										  }
										  return ResultMessage.getFailt(ResultMessage.productBatchError);
									  }
									  return ResultMessage.getFailt(ResultMessage.shopexistOrUserError);
								  }
							  }
						  }
			    	  }
			    	  return ResultMessage.getFailt(ResultMessage.busError);
			      }
			      return ResultMessage.getFailt(ResultMessage.provincialError);
		      }
		     return ResultMessage.getFailt(ResultMessage.operatorsError);
		}
		return result;
	}

	@Path("findPageDownProduct")
	@POST
	public String findPageDownProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService,"start","pageSize","operatoruid","provinceuuid","discount",
				"busuuid","useruuid","downprouuid","downfacevalue","fastchargetype","validity");
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			Map<String, Object> parameters = MapUtil.getMap();
			String token = request.getHeader("token");
			if (token != null) {
				DecodedJWT jwt;
				try {
					jwt = JWT.decode(token);
					if (jwt != null) {
						JSONObject jsonToken = JsonUtils.converToJson(jwt.getSubject());
						if (jsonToken != null) {

							User login = userService.findByUserid(jsonToken.getString(Config.tokenSignAttr));
							//如果是下游客户 只能导出一个月的
							if (login != null && UserUtil.checkRoleDown(login)) {
								parameters.put(":useruuid", new String[]{login.getUseruuid()});
							}
						}
					}
				}catch (Exception e){
				}
			}
			return ResultMessage.getSucceed( JsonUtils.excludes(this.productService.findPageDownshopproduct(getPageMap(parameters, json), json.getInt("start"), json.getInt("pageSize")),
					new String[]{"operatorsType","errorCodesForUseruuid","busuuid","","code","operatoruid","provincestatus","provinceuuid","lastlogintime",
							"password","token","userstatus","useruuid","wechatid","busCode","provincecode"}));
		}
		return result;
	}

	@Path("findAllDownProduct")
	@POST
	public String findAllDownProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "useruuid");
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			return ResultMessage.getSucceed( JsonUtils.convertListToJson(this.productService.getProductList(json.getString("useruuid")),
					new String[]{"operatorsType","errorCodesForUseruuid","busuuid","","code","operatoruid","provincestatus","provinceuuid","lastlogintime",
							"password","token","userstatus","useruuid","wechatid","busCode","provincecode","user"}));
		}
		return result;
	}

	private Map<String, Object> getPageMap(Map<String, Object> parameters,JSONObject json){
		if(!StringUtils.isBlank(json.getString("downprouuid"))){
			parameters.put(":downprouuid", json.getString("downprouuid").trim());
		}
		if(!StringUtils.isBlank(json.getString("operatoruid"))){
			parameters.put(":operatoruid", json.getString("operatoruid"));
		}
		if(!StringUtils.isBlank(json.getString("provinceuuid"))){
			parameters.put(":provinceuuid", json.getString("provinceuuid"));
		}
		if(!StringUtils.isBlank(json.getString("busuuid"))){
			parameters.put(":busuuid", json.getString("busuuid"));
		}
		if(!StringUtils.isBlank(json.getString("downfacevalue"))){
			parameters.put(":downfacevalue", (json.getString("downfacevalue")));
		}
		if(!StringUtils.isBlank(json.getString("fastchargetype"))){
			parameters.put(":fastchargetype", json.getInt("fastchargetype"));
		}
		if(!StringUtils.isBlank(json.getString("useruuid"))){
			parameters.put(":useruuid", json.getString("useruuid"));
		}
		if(json.containsKey("validity") && !StringUtils.isBlank(json.getString("validity"))){
			parameters.put(":validity", json.getString("validity"));
		}
		if(json.containsKey("cityName") && !StringUtils.isBlank(json.getString("cityName"))){
			parameters.put(":cityName", json.getString("cityName"));
		}

		if(json.containsKey("auto") && !StringUtils.isBlank(json.getString("auto"))){
			parameters.put(":auto", json.getInt("auto"));
		}

		if(json.containsKey("status") && !StringUtils.isBlank(json.getString("status"))){
			parameters.put(":status", json.getInt("status"));
		}
		if(json.containsKey("discount") && !StringUtils.isBlank(json.getString("discount"))){
			parameters.put(":discount", BigUtil.getBigDecimal(json.getString("discount")));
		}
		return parameters;
	}
	@Path("exportDownProduct")
	@POST
	public String exportDownProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data,request, userService, "operatoruid","provinceuuid",
				"busuuid","useruuid","downprouuid","downfacevalue","fastchargetype");
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			Map<String, Object> parameters = MapUtil.getMap();
			if (!json.getString("useruuid").isEmpty()) {
				if(json.containsKey("useruuid")&& json.getJSONArray("useruuid").size() > 0){
					//到导出第0个
					User login = userService.findByUserid(json.getJSONArray("useruuid").getString(0));

					JSONObject obj = JsonUtils.getJSONOBJCT();
					String exportResult = ExportExcelUtil.exportDownProduct(this.productService.exportDownCount(getPageMap(parameters, json)),login.getUsername());
					if(exportResult != null){
						obj.put("path",CookieRedis.get("download").concat(File.separator) + exportResult.replace(CookieRedis.get("exportPath"), ""));
						return ResultMessage.getSucceed(obj.toString());
					}else{
						return ResultMessage.getFailt("");
					}
				}
				return ResultMessage.getFailt("请选择分销商");
			}else{
				return ResultMessage.getFailt("请选择分销商");
			}
		}
		return result;
	}


	@POST
	@Path("findOneProduct")
	public String findOneProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "downprouuid");
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			return ResultMessage.getSucceed( JsonUtils.excludes(this.productService.findById(json.getString("downprouuid")), new String[]{"operatorsType","errorCodesForUseruuid",
					"","status","code","","provincestatus","","lastlogintime",
					"password","token","userstatus","","wechatid","busCode","modifytime","provincecode"}));
		}
		return result ;
	}
	@POST
	@Path("updateProduct")
	public String updateProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "provinceuuid","operatoruid","busuuid","useruuid","productCode",
				"downfacevalue","fastchargetype","downfailnum","downtimeinterva","remark","discount","downprouuid","price","discountAmount","productName","validity");
		if(result == null){
			   JSONObject json = JsonUtils.converToJson(data);
			      Operators operator = operatorService.findById(json.getString("operatoruid"));
			      if(operator != null){
			    	  ProvincialInformation pro = proService.findById(json.getString("provinceuuid"));
				      if(pro != null){
				    	  BusinessType busType = busService.findById(json.getString("busuuid"));
				    	  if(busType != null){
							  String token = request.getHeader("token");
							  if (token != null) {
								  DecodedJWT jwt;
								  jwt = JWT.decode(token);
								  if (jwt != null) {
									  JSONObject jsonUser = JsonUtils.converToJson(jwt.getSubject());
									  if (json != null) {
										  User user = userService.findByUserid(jsonUser.getString(Config.tokenSignAttr));
										  DownShopProduct product = this.productService.findById(json.getString("downprouuid"));
										  //				    			  DownShopProduct old = this.productService.findByIdAndProductCode(json.getString("useruuid"),json.getString("productCode"));
										  //				    			  if(old != null && product != null && !old.getDownprouuid().equals(product.getDownprouuid())){
										  //				    				  return ResultMessage.getFailt(ResultMessage.productCodeexistError);
										  //				    			  }
										  if (product != null) {
											  product.setBusinessType(busType);
											  product.setOperators(operator);
											  product.setProvincialInformation(pro);
											  //product.setUser(user);
											  product.setProductCode(json.getString("productCode"));
											  product.setDownfacevalue(json.getString("downfacevalue").trim());
											  product.setPrice(BigUtil.getBigDecimal(json.getString("price").trim()));
											  product.setFastchargetype(json.getInt("fastchargetype"));
											  product.setDownfailnum(json.getInt("downfailnum"));
											  product.setDowntimeinterva(json.getInt("downtimeinterva"));
											  product.setRemark(json.getString("remark"));
											  product.setDiscount(BigUtil.getBigDecimal(json.getString("discount").trim()));
											  product.setDiscountAmount(BigUtil.getBigDecimal(json.getString("discountAmount").trim()));
											  product.setModifytime(DateUtils.getNowDate());
											  product.setProductName(json.getString("productName"));
											  product.setValidity((json.getString("validity")));
											  product.setCityName(json.containsKey("cityName") ? json.getString("cityName") : "");

											  if (productService.updateDownshopproduct(product, user,false)) {
												  return ResultMessage.getSucceed(null);
											  }
											  return ResultMessage.getFailt("");
										  }
									  }
								  }
				    			  return ResultMessage.getFailt(ResultMessage.productexistError);
				    		  }
				    		  return ResultMessage.getFailt(ResultMessage.shopexistOrUserError);
				    	  }
				    	  return ResultMessage.getFailt(ResultMessage.busError);
				      }
				      return ResultMessage.getFailt(ResultMessage.provincialError);
			      }
			     return ResultMessage.getFailt(ResultMessage.operatorsError);
		}
		return result;
	}

	@POST
	@Path("findProductLog")
	public String findProductLog(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "downprouuid","useruuid");
		if(result == null){

		}
		return result;

	}
	@POST
	@Path("productDownEnable")
	public String productDownEnable(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "downprouuid","status","useruuid");
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			DownShopProduct downProduct = this.productService.findById(json.getString("downprouuid"));
			User user = this.userService.findByUserid(json.getString("useruuid"));
			if(downProduct != null && user != null && UserUtil.checkRole(user)){
				downProduct.setStatus(Integer.valueOf(json.getString("status")));
				this.productService.updateDownshopproduct(downProduct, user,true);
				return ResultMessage.getSucceed(null);
			}
			return ResultMessage.getFailt( "产品错误");
		}
		return result;

	}


	/**
	 * 查询上游产品是不是被匹配过
	 * @param data
	 * @param request
	 * @return
	 */
	@SuppressWarnings("static-access")
	@POST
	@Path("findByProductFetchInclu")
	public String findByProductFetchInclu(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "downuuid","operatoruid","provinceuuid","busuuid","downprouuid");
		if(result == null){
			JSONObject json = JSONObject.fromObject(data);
			MatchingStrategy match = this.matchService.findByProductFetchIncluDown(json.getString("downprouuid"),json.getString("uporderuuid"));
			if(match == null){
				match = this.matchService.findByDownUuid(json.getString("downuuid"),json.getString("provinceuuid"),
						json.getString("operatoruid"),json.getString("busuuid"));

				if(match != null){
					match.setStatus("2");
				}
			}else{
				match.setStatus("1");
			}
			return ResultMessage.getSucceed(  match != null ?
					JsonUtils.convertObjectToJson(match,new String[]{"downUser","errorCodesForUseruuid","password","phonenum"}) : "");
		}
		return result;
	}

	@Path("editHandleBatchPhoneEdit")
	@POST
	public String editHandleBatchPhoneEdit(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "provinceuuid","operatoruid","busuuid","useruuid","fastchargetype","downfailnum","downtimeinterva","products");
		if(result == null){
		      JSONObject json = JsonUtils.converToJson(data);
		      Operators operator = operatorService.findById(json.getString("operatoruid"));
		      if(operator != null){
		    	  ProvincialInformation pro = proService.findById(json.getString("provinceuuid"));
			      if(pro != null){
			    	  BusinessType busType = busService.findById(json.getString("busuuid"));
			    	  if(busType != null){
			    		  User user = userService.findByUserid(json.getString("useruuid"));
			    		  if(user != null && UserUtil.checkRoleDown(user)){
			    			  JSONArray pros = json.getJSONArray("products");
			    			  if(pros != null && !pros.isEmpty()){
			    				  for(int i = 0 ; i < pros.size(); i++){

			    					  DownShopProduct product = this.productService.findById(pros.getJSONObject(i).getString("downprouuid"));
				    				  if(product == null){
				    					  return ResultMessage.getFailt("");
				    				  }else{
				    					  product.setBusinessType(busType);
						    			  product.setOperators(operator);
						    			  product.setProvincialInformation(pro);
						    			  product.setUser(user);
				    					  product.setDownfacevalue(pros.getJSONObject(i).getString("downfacevalue"));
				    					  product.setProductCode(pros.getJSONObject(i).getString("productCode").trim());
						    			  product.setPrice(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("price").trim()));
						    			  product.setDiscount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discount").trim()));
						    			  product.setDiscountAmount(BigUtil.getBigDecimal(pros.getJSONObject(i).getString("discountAmount").trim()));
						    			  product.setProductName(pros.getJSONObject(i).getString("productName"));
										  product.setCityName(pros.getJSONObject(i).getString("cityName"));
						    			  String token = request.getHeader("token");
						    				if (token != null) {
						    					DecodedJWT jwt;
					    						jwt = JWT.decode(token);
					    						if (jwt != null) {
					    							JSONObject jsonUser = JsonUtils.converToJson(jwt.getSubject());
					    							if (json != null) {
					    								User userAdmin = userService.findByUserid(jsonUser.getString(Config.tokenSignAttr));
					    								if(!productService.updateDownshopproduct(product,userAdmin,false)){
					    									return ResultMessage.getFailt("");
					    				    			}
					    							}
					    						}
						    				}
				    				  }
			    				  }
			    				  return ResultMessage.getSucceed(null);
			    			  }
			    			  return ResultMessage.getFailt(ResultMessage.productBatchError);
			    		  }
			    		  return ResultMessage.getFailt(ResultMessage.shopexistOrUserError);
			    	  }
			    	  return ResultMessage.getFailt(ResultMessage.busError);
			      }
			      return ResultMessage.getFailt(ResultMessage.provincialError);
		      }
		     return ResultMessage.getFailt(ResultMessage.operatorsError);
		}
		return result;
	}


	/**
	 * 手动切换回自动匹配 需要删除 已经建立的匹配  OrderMatchDetail  MatchingStrategy IIncludesProductService
	 * @param data
	 * @param request
	 * @return
	 */
	@Path("autoProduct")
	@POST
	public String autoProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "products","auto");
		if(result == null){
		      JSONObject json = JsonUtils.converToJson(data);
		      JSONArray products = json.getJSONArray("products");
		      for(int i = 0 ; i < products.size(); i++){
		    	  DownShopProduct product = productService.findById(products.getJSONObject(i).getString("downprouuid"));
			      if(product != null){
			    	  product.setAuto(json.getInt("auto"));
			    	  String token = request.getHeader("token");
		  				if (token != null) {
		  					DecodedJWT jwt;
							jwt = JWT.decode(token);
							if (jwt != null) {
								JSONObject jsonUser = JsonUtils.converToJson(jwt.getSubject());
								if (json != null) {
									User userAdmin = userService.findByUserid(jsonUser.getString(Config.tokenSignAttr));
									 if(UserUtil.checkRole(userAdmin)){
										 productService.updateDownshopProduct(product.getUser(),product);
					    			  }
								}
							}
		  				}
			      }
		      }
		      return ResultMessage.getSucceed(null);
		}
		return result;
	}

	@Path("handleBatchClose")
	@POST
	public String handleBatchClose(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "products","status");
		if(result == null){
			return productService.handleBatchStatus(data,request.getHeader("token"));
		}
		return result;
	}



	@Path("findByUuidDownProduct")
	@POST
	public String findByUuidDownProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "useruuid");
		if(result == null){
		      JSONObject json = JsonUtils.converToJson(data);
		      return ResultMessage.getSucceed(JsonUtils.convertListToJson(this.productService.findByUuidDown(json.getString("useruuid")),
		    		  new String[]{"provincialInformation","operators","businessType","user","downfacevalue","discount","status",
		    				  "productCode","validity","auto","discountAmount","price","remark","downtimeinterva","downfailnum","fastchargetype",
		    				  "modifytime","createtime"}));
		}
		return result;
	}

	@Path("deleteDownProduct")
	@POST
	public String deleteDownProduct(String data,@Context HttpServletRequest request){
		String result = this.validationParameterGetRole(request, userService);
		if(result == null){
			return productService.deleteDownProduct(data);
		}
		return result;
	}
}
